//请求用  
var rule_request = {};
//请求用
var proto_request = {};
//请求用
var proto_field_request = {};
//编辑用
var editmodel = [];
//编辑用
var tag_editmodel = [];
//表格用
var tablelist = [];
//选择框用
var protolist = []
//穿越用
var protofeild = []
//存储选择框文字变量
var protoName

var storage_rule_select = []

var storage_rule_select_obj_arr = []

var transferIdGroup = []
//穿越用
var database_tbl_obj = []

var sgmt_tbls_modify_id = 0;

$.ajax({
	url: 'http://' + ipm + ':8081/dict/query',
	type: 'POST',
	contentType: 'application/json',
	dataType: 'json',
	data: {},
	success: function (response) {
		console.log(response);
		createStorageRulesObj(response);
		console.log(storage_rule_select)

		ruleRead(response);
		//createProtoselectobj(response);
		createProtofieldobj(response);
		createProtoObj(response);
		createDatabaseTblObj(response)
		// console.log(database_tbl_obj);
		createTransfer()
		// console.log(proto_field_request.protocol_segments);
		// console.log(tablelist);
		// console.log(protoselect);

		for (var i = 0; i < storage_rule_select.length; i++) {
			var storage_rule_select_obj = {}
			// storage_rule_select_obj.value = JSON.stringify(storage_rule_select[i]);
			// console.log(storage_rule_select[i].expired)

			storage_rule_select_obj.value = storage_rule_select[i].id + "," + storage_rule_select[i].name;
			// console.log(storage_rule_select_obj.value)
			// console.log(storage_rule_select_obj.value.split("|"))

			storage_rule_select_obj.text = storage_rule_select[i].name;
			storage_rule_select_obj_arr.push(storage_rule_select_obj);
			// console.log(storage_rule_select_obj_arr)

		}

		for (var i = 0; i < 10; i++) {
			if (storage_rule_select_obj_arr) {
				createTab();
			} else {
				alert('加载失败，请刷新重试')
			}
		}
		//下拉菜单赋值
		layui.use(['form', 'upload', 'layer', 'table'], function () {
			var form = layui.form;
			//使用循环遍历，给下拉列表赋值
			$.each(protolist, function (index, value) {
				$('#dp').append(new Option(value.name, value.name + ":" + value.segment_list + ";" + JSON.stringify(value.segment_tag_obj)));// 下拉菜单里添加元素
			});
			$.each(storage_rule_select, function (index, value) {
				$('#storage_rule').append(new Option(value.name, JSON.stringify(value)));// 下拉菜单里添加元素
			});
			console.log(protolist);


			$(document).ready(function () {
				// select下拉框选中触发事件
				form.on('select(xmFilter)', function (data) {
					console.log(data.value);
					var index1 = data.value.indexOf(':')
					var index2 = data.value.indexOf(';')
					var dataA = data.value.substring(index1 + 1, index2)
					console.log(dataA);

					var idArr = dataA.split(",")
					// console.log(idArr);
					var pfrArr = proto_field_request.protocol_segments
					// console.log(pfrArr);
					var showtablelist = []
					for (var i = 0; i < idArr.length; i++) {
						for (var j = 0; j < pfrArr.length; j++) {
							if (pfrArr[j].id == parseInt(idArr[i])) {
								var showObj = {
									"name": "",
									"value_type": "",
									"value_length": "",
								}
								showObj.name = pfrArr[j].name
								showObj.value_type = pfrArr[j].value_type
								showObj.value_length = pfrArr[j].value_length
								showtablelist.push(showObj)
							}
						}
					}
					// console.log(showtablelist);
					$("#showTable").bootstrapTable('destroy').bootstrapTable({
						data: showtablelist,
						dataType: 'json',
						striped: true,                      //是否显示行间隔色
						cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
						pagination: false,                   //是否显示分页（*）
						sortable: false,                     //是否启用排序
						sortOrder: "asc",                   //排序方式
						sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
						pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
						pageSize: 5,                     //每页的记录行数（*）
						search: false,                      //是否显示表格搜索
						strictSearch: true,
						showColumns: false,                  //是否显示所有的列（选择显示的列）
						showRefresh: false,                  //是否显示刷新按钮
						showExport: false,
						minimumCountColumns: 1,             //最少允许的列数
						clickToSelect: false,                //是否启用点击选中行
						height: 245,
						columns: [{
							field: 'name',
							align: 'center',
							title: '字段名称',
							width: 80,
						}, {
							field: 'value_type',
							align: 'center',
							title: '字段类型',
							width: 160,
						}, {
							field: 'value_length',
							align: 'center',
							title: '字段长度',
							width: 140,
						}
						]
					});
					// var confirmTextA = "字段 : " + data.value;
					var opt = document.getElementById("dp").name
					console.log(opt);
					protoName = data.elem[data.elem.selectedIndex].text;
					console.log(protoName);
					// document.getElementById('proto').value = protoName;
					// $("#textA").text(confirmTextA);
				});
			});

			form.render("select");
		});
	}
});



function refreshTab() {
	$.ajax({
		url: 'http://' + ipm + ':8081/dict/query',
		type: 'POST',
		contentType: 'application/json',
		dataType: 'json',
		data: {},
		success: function (response) {
			console.log(response);
			tablelist = [];
			ruleRead(response);
		}
	});
}

function createTab() {
	$("#table_page").bootstrapTable('destroy').bootstrapTable({
		data: tablelist,
		dataType: 'json',
		striped: true,                      //是否显示行间隔色
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		pagination: true,                   //是否显示分页（*）
		sortable: true,                     //是否启用排序
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 10,                     //每页的记录行数（*）
		pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
		search: false,                      //是否显示表格搜索
		strictSearch: true,
		minimumCountColumns: 1,             //最少允许的列数
		clickToSelect: true,                //是否启用点击选中行
		uniqueId: "id",                     //每一行的唯一标识，一般为主键列
		cardView: false,                    //是否显示详细视图
		detailView: false,                  //是否显示父子表
		onEditableSave: onRuleEditableSave,
		columns: [
			{
				field: 'rule_name',
				title: '规则名称',
				editable: editable_cn
			}, {
				field: 'dstip',
				title: '目的IP',
				editable: editable_cn
			}, {
				field: 'dst_port',
				title: '目的端口',
				editable: {
					type: 'number',
					min: 0,
					max: 65535
				}
			}, {
				field: 'proto_name',
				title: '协议名称'
			}, {
				field: 'ID',
				title: '编辑标签',
				width: 120,
				align: 'center',
				valign: 'middle',
				formatter: function (value, row, index) {
					var result = "";
					result += "<a href='javascript:;' class='btn btn-xs blue' onclick=\"EditTagById('" + value + "','" + row + "')\" title='编辑'><span class='feather-edit'></span></a>";
					return result;
				}
			},
			{
				field: 'proc_method',
				title: '处理方式',
				editable: {
					type: 'select',
					title: '值类型',
					emptytext: '未定义',
					source: [{
						value: "database",
						text: "存数据库"
					}, {
						value: "rawdata",
						text: "数据落盘"
					}, {
						value: "database_rawdata",
						text: "存数据库和数据落盘"
					}]
				}
			}, {
				field: 'sgmt_tbls',
				align: 'center',
				title: '数据库表',
				width: 60,
				formatter: function (value, row, index) {
					var result = "";
					result += "<a href='javascript:;' class='btn btn-xs blue' onclick=\"arr_Dbtbls_modify('" + index + "','" + value + "')\" title='编辑'><span class='feather-edit'></span></a>";
					return result;
				}
			}, 
			 {
				field: 'storage_rule',
				align: 'center',
				title: '存储规则',
				editable: {
					type: 'select',
					title: '值类型',
					emptytext: '未定义',
					source: storage_rule_select_obj_arr
				}
			},
			// {
			// 	field: 'expired_val',
			// 	title: '存储时长',
			// 	editable: timeLimit
			// }, {
			// 	field: 'expired_unit',
			// 	title: '时长单位',
			// 	editable: {
			// 		type: 'select',
			// 		title: '值类型',
			// 		source: [{
			// 			value: "year",
			// 			text: "年"
			// 		}, {
			// 			value: "month",
			// 			text: "月"
			// 		}, {
			// 			value: "day",
			// 			text: "天"
			// 		}, {
			// 			value: "hour",
			// 			text: "小时"
			// 		}, {
			// 			value: "min",
			// 			text: "分钟"
			// 		}]
			// 	}
			// },
			// {
			// 	field: 'level',
			// 	title: '数据等级',
			// 	editable: {
			// 		type: 'select',
			// 		title: '值类型',
			// 		source: [{
			// 			value: "1",
			// 			text: "1"
			// 		}, {
			// 			value: "2",
			// 			text: "2"
			// 		}, {
			// 			value: "3",
			// 			text: "3"
			// 		}, {
			// 			value: "4",
			// 			text: "4"
			// 		}, {
			// 			value: "5",
			// 			text: "5"
			// 		}]
			// 	}
			// },
			{
				field: 'enabled',
				title: '使能',
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "start",
						text: "启用"
					}, {
						value: "pause",
						text: "暂停"
					}, {
						value: "continue",
						text: "恢复"
					}, {
						value: "stop",
						text: "停止"
					}]
				}
			}, {
				field: 'id',
				title: '操作',
				width: 120,
				align: 'center',
				valign: 'middle',
				formatter: actionFormatterD
			}

		],
	});


}

// //时间输入限制
// function timeLimit(rowIndex) {
// 	// console.log(rowIndex)
// 	var data = $("#table_page").bootstrapTable('getData');
// 	// console.log(data[rowIndex].expired_unit)

// 	if (data[rowIndex].expired_unit == "year") {
// 		return {
// 			type: 'number',
// 			min: 1,
// 			max: 100
// 		}
// 	} else if (data[rowIndex].expired_unit == "month") {
// 		return {
// 			type: 'number',
// 			min: 1,
// 			max: 11
// 		}
// 	} else if (data[rowIndex].expired_unit == "day") {
// 		return {
// 			type: 'number',
// 			min: 1,
// 			max: 29
// 		}
// 	} else if (data[rowIndex].expired_unit == "hour") {
// 		return {
// 			type: 'number',
// 			min: 1,
// 			max: 23
// 		}
// 	} else if (data[rowIndex].expired_unit == "min") {
// 		return {
// 			type: 'number',
// 			min: 1,
// 			max: 59
// 		}
// 	}


// }


function SavdRuleByIds(args, values) {
	var count = $("#table" + args).bootstrapTable('getSelections');
	console.log(count)
	var offset = []
	for (var i = 0; i < count.length; i++) {
		offset.push(count[i].ID - 1)
	}

	var arr = rule_request.proto_rules;
	console.log(arr)
	console.log(values)
	for (var i = 0; i < arr.length; i++) {
		if (arr[i].id == values) {
			arr[i].sgmt_offlist = offset;
		}
	}
	console.log(offset)
	var ruleWeb = {
		"cfgType": "5",
		"cfgName": "proto_rules.json",
		"content": ""
	}
	var ruleSave = {
		"cfg_type": 5,
		"clean_data_interval": 10,
		"rule_max_id": "",
		"proto_rules": ""
	}
	ruleSave.proto_rules = arr;
	ruleSave.rule_max_id = rule_request.rule_max_id;
	ruleWeb.content = JSON.stringify(ruleSave)
	postQuestSave(ruleWeb);
	window.location.reload();
}

function getProtocolByName(name) {
	for (var i = 0; i < protolist.length; i++) {
		if (protolist[i].name == name) {
			console.log(protolist[i]);
			return protolist[i];
		}
	}
}



function actionFormatterD(value, row, index) {

	var result = "";
	result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"rule_modify('" + value + "')\" title='删除'><span class='feather-trash-2'></span></a>";
	return result;
}

//编辑保存
function onRuleEditableSave(field, row, rowIndex, oldValue, $el) {
	var data = $("#table_page").bootstrapTable('getData');
	var objChange = data[rowIndex];
	var idChange = objChange.id;
	var arr = rule_request.proto_rules;
	var ruleWeb = {
		"cfgType": "5",
		"cfgName": "proto_rules.json",
		"content": ""
	}
	var ruleSave = {
		"cfg_type": 5,
		"clean_data_interval": 10,
		"rule_max_id": "",
		"proto_rules": ""
	}
	if (field == "dstip") {

		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dstip = row[field];
			}
		}
	} else if (field == "rule_name") {

		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].rule_name = row[field];
			}
		}
	} else if (field == "dst_port") {

		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dst_port = parseInt(row[field]);
			}
		}
	} else if (field == "proc_method") {

		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].proc_method = row[field];
			}
		}
	} 
	// else if (field == "level") {

	// 	for (var i = 0; i < arr.length; i++) {
	// 		if (arr[i].id == idChange) {
	// 			arr[i].level = parseInt(row[field]);
	// 		}
	// 	}
	// } 
	else if (field == "storage_rule") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				console.log(storage_rule_select)
				// arr[i].storage_rule =  JSON.parse(row[field]);
				var changeObj = row[field].split(",")
				// arr[i].storage_rule.id = parseInt(changeObj[0]);
				// console.log(parseInt(changeObj[0]))
				// arr[i].storage_rule.name = changeObj[1];
				// console.log(changeObj)
				// // console.log(row[field])
				// // console.log(changeObj[2])
				// arr[i].storage_rule.expired = JSON.parse(changeObj[2]);
				for (var j = 0; j < storage_rule_select.length; j++) {
					if (storage_rule_select[j].id == changeObj[0]) {
						var storage_rule_new = {
							"id": "",
							"name": ""
						}
						storage_rule_new.id = storage_rule_select[j].id
						storage_rule_new.name = storage_rule_select[j].name
						// storage_rule_new.expired = storage_rule_select[j].expired
						// storage_rule_new.level = storage_rule_select[j].level
						console.log(storage_rule_new)
						console.log(storage_rule_select[j].expired)
						arr[i].storage_rule = storage_rule_new
						arr[i].expired = storage_rule_select[j].expired
						arr[i].level = storage_rule_select[j].level
					}
				}
				// console.log(arr[i].storage_rule)
				// console.log(arr[i].expired)

			}
		}
	} else if (field == "enabled") {

		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				//console.log(row[field])
				// arr[i].enabled = JSON.parse(row[field].toLowerCase())
				if (row[field] == "start") {
					// arr[i].enabled = JSON.parse(row[field].toLowerCase())
					arr[i].enabled = true
					arr[i].button = "start"
				} else if (row[field] == "stop") {
					arr[i].enabled = false
					arr[i].button = "stop"
				} else if (row[field] == "continue") {
					arr[i].enabled = true
					arr[i].button = "continue"
				} else if (row[field] == "pause") {
					arr[i].enabled = false
					arr[i].button = "pause"
				}//console.log(JSON.parse(row[field].toLowerCase()))
			}
		}
	}
	ruleSave.proto_rules = arr;
	ruleSave.rule_max_id = rule_request.rule_max_id;
	ruleWeb.content = JSON.stringify(ruleSave)
	console.log(ruleSave)
	// postQuestSave(ruleWeb);
	////////////////////////////////////////////////
	////////////////请求发送并重新建表///////////////
	////////////////////////////////////////////////
	var xhr = new XMLHttpRequest();
	// 配置请求
	xhr.open('POST', 'http://' + ipm + ':8081/dict/save', true);
	xhr.setRequestHeader('content-Type', 'application/json');
	// 发送 JSON 数据
	xhr.send(JSON.stringify(ruleWeb));
	// 监听请求的状态
	xhr.onreadystatechange = function () {
		console.log(xhr.readyState);
		if (xhr.readyState === 4 && xhr.status === 200) {
			console.log(xhr.responseText);
			$.ajax({
				url: 'http://' + ipm + ':8081/dict/query',
				type: 'POST',
				contentType: 'application/json',
				dataType: 'json',
				data: {},
				success: function (response) {
					tablelist = []
					console.log(response);
					ruleRead(response);
					createTab()
				}
			});

		}
	};
	layer.msg('修改成功', { icon: 1 });
}


//新增规则模态框构建
function createRuleModel() {
	$('#ruleModal').modal('show');

}




layui.config({
	base: 'step-lay/'
}).use(['form', 'step'], function () {
	var $ = layui.$
		, form = layui.form
		, step = layui.step;

	step.render({
		elem: '#stepForm',
		filter: 'stepForm',
		width: '100%', //设置容器宽度
		stepWidth: '750px',
		height: '600px',
		stepItems: [{
			title: '名称配置'
		}, {
			title: '数据处理配置'
		}, {
			title: '完成'
		}]
	});


	form.on('submit(formStep)', function (data) {
		step.next('#stepForm');
		return false;
	});

	form.on('submit(formStep2)', function (data) {
		step.next('#stepForm');
		return false;
	});

	$('.pre').click(function () {
		step.pre('#stepForm');
	});

	$('.next').click(function () {
		step.next('#stepForm');
	});
})


var field
var transferIdGroup = []
layui.use(['form', 'upload', 'layer'], function () {
	var form = layui.form;

	//方法提交
	$('#testSubmitBtn').on('click', function (data) {
		form.submit('rule', function (data) { // 注：v2.7.0 新增
			// 回调函数返回结果跟上述 submit 事件完全一致
			field = data.field;
			console.log(data.field)
			// do something
			buildRuleJson();
		});
		return false;
	});

	//隐藏长度框
	form.on('select(method)', function (data) {
		console.log(data.value);
		if (data.value == "database") {
			// $('#storage_rule').empty();
			$('#database_table').show();
			// $('#storage_rule_div').hide();
		} else if (data.value == "rawdata") {
			// $('#storage_rule').empty();
			// $('#storage_rule_div').show();
			$('#database_table').hide();
		} else if (data.value == "database_rawdata") {
			// $('#storage_rule').empty();
			$('#database_table').show();
			// $('#storage_rule_div').show();
		}
		form.render('select');
	});

});



//增加/加入一个协议数据规则JSON
function buildRuleJson() {
	var arrRule = rule_request.proto_rules;
	var id = rule_request.rule_max_id;
	id++;

	var ruleWeb = {
		"cfgType": "5",
		"cfgName": "proto_rules.json",
		"content": ""
	}

	var ruleSave = {
		"cfg_type": 5,
		"clean_data_interval": 10,
		"rule_max_id": "",
		"proto_rules": ""
	}

	if (id) {
		rules = {
			"id": "",
			"rule_name": "",
			"dstip": "",
			"dst_port": "",
			"proto_name": "",
			"segment_tag": [],
			"sgmt_tbls": [1, 2, 3, 5],
			"proc_method": "",
			"expired": "",
			"level": "",
			"storage_rule": { "id": 1, "name": "航迹c" },
			"enabled": true,
			"button": "start"
		}
		rules.id = id;
	} else {
		arrRule = []
		rules = {
			"id": "",
			"rule_name": "",
			"dstip": "",
			"dst_port": "",
			"proto_name": "",
			"segment_tag": [],
			"sgmt_tbls": [1, 2, 3, 5],
			"proc_method": "",
			"expired": "",
			"level": "",
			"storage_rule": { "id": 1, "name": "航迹c" },
			"enabled": true,
			"button": "start"

		}
		id = 0;
		rules.id = 0;
	}
	console.log(field);
	rules.rule_name = field.rule_name;
	rules.dstip = field.ip1 + "." + field.ip2 + "." + field.ip3 + "." + field.ip4;
	rules.dst_port = parseInt(field.port);
	rules.proto_name = protoName;
	rules.sgmt_tbls = transferIdGroup;
	rules.proc_method = field.method;
	// var expired_save = {
	// 	"val": "",
	// 	"unit": ""
	// }
	// expired_save.val = parseInt(field.expired_value)
	// expired_save.unit = field.expired_select

	// if (field.expired_select == "year") {
	// 	expired_save.val = parseInt(field.expired_value) * 365
	// 	expired_save.unit = "day"
	// } else if (field.expired_select == "month") {
	// 	expired_save.val = parseInt(field.expired_value) * 30
	// 	expired_save.unit = "day"
	// } else if (field.expired_select == "day") {
	// 	expired_save.val = parseInt(field.expired_value)
	// 	expired_save.unit = "day"
	// } else if (field.expired_select == "hour") {
	// 	expired_save.val = parseInt(field.expired_value)
	// 	expired_save.unit = "hour"
	// } else if (field.expired_select == "min") {
	// 	expired_save.val = parseInt(field.expired_value)
	// 	expired_save.unit = "min"
	// }
	// expired_save.val = parseInt(field.expired_value)
	// expired_save.unit = field.expired_select
	// rules.expired = expired_save
	// rules.expired = parseInt(field.expired1) * 365 + parseInt(field.expired2) * 30 + parseInt(field.expired3);
	// rules.level = parseInt(field.level);
	// if (field.method == "rawdata" || field.method == "database_rawdata") {
	rules.storage_rule.id = JSON.parse(field.storage_rule).id;
	rules.storage_rule.name = JSON.parse(field.storage_rule).name;
	// rules.storage_rule.expired = JSON.parse(field.storage_rule).expired;
	// rules.storage_rule.level = JSON.parse(field.storage_rule).level;

	// } else if (field.method == "database") {
	// 	rules.storage_rule.id = -1;
	// 	rules.storage_rule.name = "";
	// 	rules.storage_rule.expired = {
	// 		"val": -1,
	// 		"unit": ""
	// 	}
	// }
	rules.expired = JSON.parse(field.storage_rule).expired;
	rules.level = JSON.parse(field.storage_rule).level;
	var register = $("#tagConfigForm");
	var formData = register.serializeArray();
	var json = []
	for (var j = 0; j < formData.length; j++) {
		var obj = {}
		formData[j].name = "id";
		formData[j + 1].name = "tag";
		obj[formData[j].name] = parseInt(formData[j]['value']);
		console.log(isHexadecimal(formData[j + 1]['value']))
		if (isHexadecimal(formData[j + 1]['value']) == false) {
			alert("标识输入错误,请输入16进制数")
			return false;
		}
		obj[formData[j + 1].name] = parseInt(formData[j + 1]['value'], 16);
		json.push(obj);
		j++;
	}
	rules.segment_tag = json

	arrRule.push(rules);
	ruleSave.proto_rules = arrRule;
	ruleSave.rule_max_id = id;
	ruleWeb.content = JSON.stringify(ruleSave);
	console.log(ruleSave);
	postQuestSave(ruleWeb);
	alert("新增成功！");
	window.location.reload();

}


//查看配置tag
function lookTag() {
	var register = $("#tagConfigForm");
	var formData = register.serializeArray();
	var json = []
	for (var j = 0; j < formData.length; j++) {
		var obj = {}
		formData[j].name = "id";
		formData[j + 1].name = "tag";
		obj[formData[j].name] = parseInt(formData[j]['value']);
		console.log(isHexadecimal(formData[j + 1]['value']))
		if (isHexadecimal(formData[j + 1]['value']) == false) {
			alert("标识输入错误,请输入16进制数")
			return false;
		}
		obj[formData[j + 1].name] = parseInt(formData[j + 1]['value'], 16);
		json.push(obj);
		j++;
	}
	console.log(json);
}






//删除协议字段解析表JSON
function rule_modify(args) {

	var arrRuleWeb = []
	var ruleWeb = {
		"cfgType": "5",
		"cfgName": "proto_rules.json",
		"content": ""
	}
	ruleWeb.id = parseInt(args);
	arrRuleWeb.push(ruleWeb)
	sss = JSON.stringify(arrRuleWeb)
	console.log(sss)
	$.ajax({
		url: 'http://' + ipm + ':8081/dict/deleteProto',
		type: 'POST',
		contentType: 'application/json',
		dataType: 'json',
		data: sss,
		success: function (response) {
			console.log(response);
		}
	});
	window.location.reload();
}


//穿越框配置
function createTransfer() {
	var database_tbl_transfer = []
	for (var i = 0; i < database_tbl_obj.length; i++) {
		var obj = {
			"value": ""
			, "title": ""
		}
		var database_tbl_title = "ID：" + database_tbl_obj[i].ID + "|数据库表名：" + database_tbl_obj[i].tlbname
		obj.value = database_tbl_obj[i].id;
		obj.title = database_tbl_title;
		database_tbl_transfer.push(obj);
	}
	console.log(database_tbl_transfer);
	layui.use(['transfer', 'layer', 'util'], function () {
		var $ = layui.$
			, transfer = layui.transfer
			, layer = layui.layer
			, util = layui.util;
		//基础效果
		transfer.render({
			elem: '#test1'
			, data: database_tbl_transfer
			, id: 'key123'
			, title: ['待选数据库表', '已选数据库表']
			, showSearch: true
			, width: 300 //定义宽度
			, height: 350 //定义高度
		})
		//批量办法定事件
		util.event('lay-demoTransferActive', {
			getData: function (othis) {
				transferIdGroup = []
				var getData = transfer.getData('key123'); //获取右侧数据
				//layer.alert(JSON.stringify(getData));
				for (var i = 0; i < getData.length; i++) {
					transferIdGroup.push(getData[i].value);
				}
				console.log(transferIdGroup);
			}
		});
	});
}

//数据库表配置******
function arr_Dbtbls_config() {
	$('#databasetblsConfigModal').modal('show');
}

function arr_Dbtbls_config_hide() {
	$('#databasetblsConfigModal').modal('hide');
}


//数据库表修改
function arr_Dbtbls_modify(rowIndex, value) {
	console.log(rowIndex)
	console.log(value)
	
	if(rule_request.proto_rules[rowIndex].proc_method == "rawdata"){
		alert("需使用存数据库方式进行配置");
		return false
	}
	sgmt_tbls_modify_id = rule_request.proto_rules[rowIndex].id
	console.log(sgmt_tbls_modify_id)
	var sgmt_tbls_transfer_modify = []
	var sgmt_tbls_selected = value.split(",")
	for (var i = 0; i < database_tbl_obj.length; i++) {
		var obj = {
			"value": ""
			, "title": ""
		}
		var database_tbl_title = "ID：" + database_tbl_obj[i].ID + "|数据库表名：" + database_tbl_obj[i].tlbname
		obj.value = database_tbl_obj[i].id;
		obj.title = database_tbl_title;
		sgmt_tbls_transfer_modify.push(obj);
	}
	layui.use(['transfer', 'layer', 'util'], function () {
		var $ = layui.$
			, transfer = layui.transfer
			, layer = layui.layer
			, util = layui.util;
		//基础效果
		transfer.render({
			elem: '#test2'
			, data: sgmt_tbls_transfer_modify
			, id: 'key123'
			, title: ['待选字段', '已选字段']
			, value: sgmt_tbls_selected
			, showSearch: true
			, width: 300 //定义宽度
			, height: 350 //定义高度
		})
		//批量办法定事件
		util.event('lay-demoTransferActive', {
			getData_modify: function (othis) {
				transferIdGroup = []
				var getData = transfer.getData('key123'); //获取右侧数据
				//layer.alert(JSON.stringify(getData));
				for (var i = 0; i < getData.length; i++) {
					transferIdGroup.push(getData[i].value);
				}
				console.log(transferIdGroup);
				var arrRule = rule_request.proto_rules;
				var ruleWeb = {
					"cfgType": "5",
					"cfgName": "proto_rules.json",
					"content": ""
				}
				var ruleSave = {
					"cfg_type": 5,
					"clean_data_interval": 10,
					"rule_max_id": "",
					"proto_rules": ""
				}
				for (var i = 0; i < arrRule.length; i++) {
					if (arrRule[i].id == sgmt_tbls_modify_id) {
						arrRule[i].sgmt_tbls = transferIdGroup
					}
				}
				ruleSave.proto_rules = arrRule;
				ruleSave.rule_max_id = rule_request.rule_max_id;
				ruleWeb.content = JSON.stringify(ruleSave);
				console.log(ruleSave);
				postQuestSave(ruleWeb);
				alert("修改成功！");
			}
		});
	});
	$('#databasetblsModal').modal('show');
}

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////




//数据库表配置******
function tag_config() {
	$('#tagConfig').modal('show');
}

function tag_config_hide() {
	$('#tagConfig').modal('hide');
}





//标签配置
//插入一行tag
function addtagConfigTable() {
	var Table = document.getElementById("tag_config");
	//addId++;
	//----获取下拉框信息----
	var segment_transfer = []
	for (var i = 0; i < protofeild.length; i++) {
		var obj = {
			"value": ""
			, "title": ""
		}
		var method
		if (protofeild[i].method == "dict_name") {
			method = "字典";
		} else if (protofeild[i].method == "logical_expressions") {
			method = "逻辑表达式";
		} else if (protofeild[i].method == "parse_list_name") {
			method = "解析表";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "ascii") {
			method = "字符串";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "hex") {
			method = "原始值";
		} else if (protofeild[i].method == "strtrim") {
			method = "分隔符";
		}
		var segment_title = protofeild[i].name + "|" + protofeild[i].value_type + "|" + protofeild[i].value_length + "|" + method + "|" + protofeild[i].value;
		obj.value = protofeild[i].id;
		obj.title = segment_title;
		segment_transfer.push(obj);
	}
	var selectAddOption = "";
	var proto = document.getElementById("dp")
	var protoName = proto.options[proto.selectedIndex].text
	console.log(protolist)
	var tableArr
	for (var i = 0; i < protolist.length; i++) {
		if (protolist[i].name == protoName) {
			tableArr = protolist[i].segment_list
		}
	}
	console.log(tableArr)


	// var tableArr = protolist[currentId].segment_list;
	for (var i = 0; i < tableArr.length; i++) {
		for (var j = 0; j < segment_transfer.length; j++) {
			if (tableArr[i] == segment_transfer[j].value) {
				selectAddOption += "<option value = " + segment_transfer[j].value + ">" + segment_transfer[j].title + "</option>";
			}
		}
	}
	//----获取下拉框信息结束----
	//console.log(Table.rows)

	var rowsNum = Table.rows.length - 1;
	NewRow = Table.insertRow(); //添加行
	//添加列
	id = NewRow.insertCell();
	tag = NewRow.insertCell();
	operate = NewRow.insertCell();

	//属性赋值
	id.innerHTML = '<select id = id" + rowsNum + 1 + " Name=id" + rowsNum + 1 + " class="form-control form-control-sm"> ' + selectAddOption + ' </select>'

	//	id.innerHTML = "<input id = id" + rowsNum + 1 + " Name=id" + rowsNum + 1 + " class='form-control form-control-sm'  type='text' />";
	tag.innerHTML = "<input id = tag" + rowsNum + 1 + " Name=tag" + rowsNum + 1 + " class='form-control form-control-sm'  type='text' />";
	operate.innerHTML = '<div id=operate' + (rowsNum + 1) + '><a style="cursor:pointer;color:#007bff;"  onclick="deleteTagConfig();">取消</a></div>';

}

//删除编辑中的tag字段
function deleteTagConfig() {
	var td = event.srcElement; // 通过event.srcElement 获取激活事件的对象 td
	var key = td.parentElement.parentElement.parentNode.rowIndex;  //获取行索引
	document.getElementById("tag_config").deleteRow(key); //删除
	//addId--;
}

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

var ruleTag_room
//根据ID获取对应内容
function EditTagById(args, rows) {
	$('#myModal').modal('show');
	//$('#protoEditer').modal('show');
	console.log(rows)
	//----获取下拉框信息----
	var segment_transfer = []
	for (var i = 0; i < protofeild.length; i++) {
		var obj = {
			"value": ""
			, "title": ""
		}
		var method
		if (protofeild[i].method == "dict_name") {
			method = "字典";
		} else if (protofeild[i].method == "logical_expressions") {
			method = "逻辑表达式";
		} else if (protofeild[i].method == "parse_list_name") {
			method = "解析表";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "ascii") {
			method = "字符串";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "hex") {
			method = "原始值";
		} else if (protofeild[i].method == "strtrim") {
			method = "分隔符";
		}
		var segment_title = protofeild[i].name + "|" + protofeild[i].value_type + "|" + protofeild[i].value_length + "|" + method + "|" + protofeild[i].value;
		obj.value = protofeild[i].id;
		obj.title = segment_title;
		segment_transfer.push(obj);
	}
	var selectOption = [];
	var tableArr
	for (var i = 0; i < protolist.length; i++) {
		if (protolist[i].name == args) {
			tableArr = protolist[i].segment_list
		}
	}
	// var tableArr = protolist[args - 1].segment_list;
	var data = $("#table_page").bootstrapTable('getData');
	console.log(data);
	console.log(data[args - 1].proto_name);

	var tableArr
	var tagA = rule_request.proto_rules;
	var tagArr = tagA[args - 1].segment_tag;
	var protoName = tagA[args - 1].proto_name;
	for (var i = 0; i < protolist.length; i++) {
		if (protolist[i].name == protoName) {
			tableArr = protolist[i].segment_list
		}
	}
	console.log(segment_transfer);
	console.log(tableArr);
	console.log(tagArr);
	for (var i = 0; i < tableArr.length; i++) {
		for (var j = 0; j < segment_transfer.length; j++) {
			if (tableArr[i] == segment_transfer[j].value) {
				for (var k = 0; k < tagArr.length; k++) {
					if (tableArr[i] == tagArr[k].id) {
						selectOption[k] += "<option selected value = " + segment_transfer[j].value + ">" + segment_transfer[j].title + "</option>";
					} else {
						selectOption[k] += "<option value = " + segment_transfer[j].value + ">" + segment_transfer[j].title + "</option>";
					}
				}
			}
		}
	}
	//----获取下拉框信息结束----

	console.log(tag_editmodel)
	currentId = args - 1;
	ruleTag_room = tablelist[args - 1].id;
	var Table = document.getElementById("protoView");
	for (var rowsNum = 0; rowsNum < tag_editmodel[args - 1].length; rowsNum++) {
		if (tag_editmodel[args - 1].length > 0) {
			//console.log(editmodel[args - 1].length);
			NewRow = Table.insertRow(); //添加行
			//添加列
			id = NewRow.insertCell();
			tag = NewRow.insertCell();
			operate = NewRow.insertCell();
			//属性赋值
			id.innerHTML = '<select id = id" + rowsNum + 1 + " Name=id" + rowsNum + 1 + " class="form-control form-control-sm"> ' + selectOption[rowsNum] + ' </select>'
			tag.innerHTML = "<input id = tag" + rowsNum + 1 + " Name=tag" + rowsNum + 1 + " value=" + tag_editmodel[args - 1][rowsNum].tag.toString(16) + " class='form-control form-control-sm' type='text' />";
			operate.innerHTML = '<div id=operate' + (rowsNum + 1) + '><a style="cursor:pointer;color:#007bff;"  onclick="deleteInterfaceParam(' + (args - 1) + ');">取消</a></div>';

		}
	}

}


//插入一行tag
function addprotoEditTable() {
	var Table = document.getElementById("protoView");
	//addId++;
	//----获取下拉框信息----
	var segment_transfer = []
	for (var i = 0; i < protofeild.length; i++) {
		var obj = {
			"value": ""
			, "title": ""
		}
		var method
		if (protofeild[i].method == "dict_name") {
			method = "字典";
		} else if (protofeild[i].method == "logical_expressions") {
			method = "逻辑表达式";
		} else if (protofeild[i].method == "parse_list_name") {
			method = "解析表";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "ascii") {
			method = "字符串";
		} else if (protofeild[i].method == "string" && protofeild[i].value == "hex") {
			method = "原始值";
		} else if (protofeild[i].method == "strtrim") {
			method = "分隔符";
		}
		var segment_title = protofeild[i].name + "|" + protofeild[i].value_type + "|" + protofeild[i].value_length + "|" + method + "|" + protofeild[i].value;
		obj.value = protofeild[i].id;
		obj.title = segment_title;
		segment_transfer.push(obj);
	}
	var selectAddOption = "";
	// console.log(currentId)
	var data = $("#table_page").bootstrapTable('getData');
	// console.log(data);
	// console.log(data[currentId].proto_name);
	var tableArr
	var tagA = rule_request.proto_rules;
	var protoName = tagA[currentId].proto_name;
	for (var i = 0; i < protolist.length; i++) {
		if (protolist[i].name == protoName) {
			tableArr = protolist[i].segment_list
		}
	}

	// var tableArr = protolist[currentId].segment_list;
	for (var i = 0; i < tableArr.length; i++) {
		for (var j = 0; j < segment_transfer.length; j++) {
			if (tableArr[i] == segment_transfer[j].value) {
				selectAddOption += "<option value = " + segment_transfer[j].value + ">" + segment_transfer[j].title + "</option>";
			}
		}
	}
	//----获取下拉框信息结束----

	var rowsNum = Table.rows.length - 1;
	NewRow = Table.insertRow(); //添加行
	//添加列
	id = NewRow.insertCell();
	tag = NewRow.insertCell();
	operate = NewRow.insertCell();

	//属性赋值
	id.innerHTML = '<select id = id" + rowsNum + 1 + " Name=id" + rowsNum + 1 + " class="form-control form-control-sm"> ' + selectAddOption + ' </select>'

	//	id.innerHTML = "<input id = id" + rowsNum + 1 + " Name=id" + rowsNum + 1 + " class='form-control form-control-sm'  type='text' />";
	tag.innerHTML = "<input id = tag" + rowsNum + 1 + " Name=tag" + rowsNum + 1 + " class='form-control form-control-sm'  type='text' />";
	operate.innerHTML = '<div id=operate' + (rowsNum + 1) + '><a style="cursor:pointer;color:#007bff;"  onclick="deleteInterfaceParam();">取消</a></div>';

}

//删除编辑中的tag字段
function deleteInterfaceParam() {
	var td = event.srcElement; // 通过event.srcElement 获取激活事件的对象 td
	var key = td.parentElement.parentElement.parentNode.rowIndex;  //获取行索引
	document.getElementById("protoView").deleteRow(key); //删除
	//addId--;
}

//一个协议tag修改JSON
function buildEditProtoJson() {
	var register = $("#protoForm1");
	var formData = register.serializeArray();

	var arrRule = rule_request.proto_rules;
	var id = rule_request.rule_max_id;
	id++;

	var ruleWeb = {
		"cfgType": "5",
		"cfgName": "proto_rules.json",
		"content": ""
	}

	var ruleSave = {
		"cfg_type": 5,
		"clean_data_interval": 10,
		"rule_max_id": "",
		"proto_rules": ""
	}

	console.log(ruleTag_room)
	var json = []
	var arr = []
	for (var i = 0; i < arrRule.length; i++) {
		if (arrRule[i].id == ruleTag_room) {
			for (var j = 0; j < formData.length; j++) {
				var obj = {}
				formData[j].name = "id";
				formData[j + 1].name = "tag";
				obj[formData[j].name] = parseInt(formData[j]['value']);
				// if (parseInt(formData[j + 1]['value'], 16)) {
				// 	return true
				// } else if (parseInt(formData[j + 1]['value'], 16) == "") {
				// 	alert("0")
				// 	return false;
				// }
				console.log(isHexadecimal(formData[j + 1]['value']))
				if (isHexadecimal(formData[j + 1]['value']) == false) {
					alert("修改失败,请输入16进制数")
					return false;
				}
				// console.log(parseInt(formData[j + 1]['value'], 16))
				obj[formData[j + 1].name] = parseInt(formData[j + 1]['value'], 16);
				json.push(obj);
				j++;
			}
			console.log(json);
			arrRule[i].segment_tag = json;
			arr.push(arrRule[i]);
		} else {
			arr.push(arrRule[i]);
		}
	}
	console.log(arr);
	ruleSave.proto_rules = arr;
	ruleSave.rule_max_id = id;
	ruleWeb.content = JSON.stringify(ruleSave);
	console.log(ruleWeb);
	postQuestSave(ruleWeb);
	//refreshTab();
	alert("修改成功！")
	window.location.reload();
}


//判断是否是16进制数
function isHexadecimal(str) {
	var pattern = /^[0-9a-fA-F]+$/; // 定义只包含十六进制字符的正则表达式
	return pattern.test(str); // 返回结果
}

//模态框关闭清理
$('#myModal').on('hidden.bs.modal', function () {
	deleteprotoViewEdit();
});

//模态框清理函数
function deleteprotoViewEdit() {
	var Table = document.getElementById("protoView");
	var rows = Table.getElementsByTagName("tr").length;
	var rowsNum = 0;
	for (rowsNum; rowsNum < rows - 1; rowsNum++) {
		NewRow = Table.deleteRow(-1); //添加
	}
}

